package com.happok.onlineclass.usermanagement.authentication.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64Decoder;
import com.happok.onlineclass.usermanagement.authentication.dto.LoginResultDTO;
import com.happok.onlineclass.usermanagement.user.dataobject.UserDO;
import com.happok.onlineclass.usermanagement.user.service.UserDaoService;
import com.happok.onlineclass.usermanagement.user.service.UserPermissionDaoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;


/**
 * 接口分类                        yapi 分类文件夹
 * 功能说明
 *
 * @author : chenac
 * @module 项目名称/模块名          yapi 项目组/子项目
 * @date : 2021/7/15 15:05
 */
@Service
public class AuthenticationServiceImpl implements AuthenticationService {

    @Autowired
    private UserDaoService userDaoService;

    @Autowired
    private UserPermissionDaoService userPermissionDaoService;

    @Override
    public LoginResultDTO login(String basicAuth) {
        String decodeStr = Base64Decoder.decodeStr(basicAuth.replace("Basic ", ""));
        UserDO userDO = userDaoService.getUserByUsername(decodeStr.substring(0, decodeStr.lastIndexOf(":")));
        LoginResultDTO loginResultDTO = new LoginResultDTO();
        if (!ObjectUtils.isEmpty(userDO)) {
            BeanUtil.copyProperties(userDO, loginResultDTO);
            loginResultDTO.setForcePwdChange(userDO.getForcePassword());
            loginResultDTO.setEnterpriseAuthorityMap(userPermissionDaoService.enterpriseAuthorities(userDO.getId()));
            loginResultDTO.setPlatformAuthoritys(userPermissionDaoService.platformAuthorities(userDO.getId()));
            loginResultDTO.setTrainOrgAuthorityMap(userPermissionDaoService.trainOrgAuthorities(userDO.getId()));
        }
        return loginResultDTO;
    }

    @Override
    public LoginResultDTO loginAccount(String account) {
        UserDO userDO = userDaoService.getUserByUsername(account);
        LoginResultDTO loginResultDTO = new LoginResultDTO();
        if (!ObjectUtils.isEmpty(userDO)) {
            BeanUtil.copyProperties(userDO, loginResultDTO);
            loginResultDTO.setForcePwdChange(userDO.getForcePassword());
            loginResultDTO.setEnterpriseAuthorityMap(userPermissionDaoService.enterpriseAuthorities(userDO.getId()));
            loginResultDTO.setPlatformAuthoritys(userPermissionDaoService.platformAuthorities(userDO.getId()));
            loginResultDTO.setTrainOrgAuthorityMap(userPermissionDaoService.trainOrgAuthorities(userDO.getId()));
        }
        return loginResultDTO;
    }
}